#!/bin/bash
#set -e
IMG=redis:7.0-alpine
NET=redis-net
SUBNET=172.30.0.0/24

# 1. 清旧环境
docker rm -f redis-master redis-slave1 redis-slave2 sentinel1 sentinel2 sentinel3 2>/dev/null
docker network rm $NET 2>/dev/null

# 2. 创建自定义桥接网络
docker network create --subnet $SUBNET --gateway 172.30.0.1 $NET

# 3. 目录
mkdir -p /opt/redis/{master,slave1,slave2,sentinel{1..3}}/data

# 4. 主配置
cat >/opt/redis/master/redis.conf <<'EOF'
bind 0.0.0.0
port 6379
protected-mode no
daemonize no
requirepass 123456
masterauth 123456
appendonly yes
dir /data
EOF

# 5. 从配置
for n in slave1 slave2; do
cat >/opt/redis/$n/redis.conf <<'EOF'
bind 0.0.0.0
port 6379
protected-mode no
daemonize no
requirepass 123456
masterauth 123456
replicaof 172.30.0.2 6379
appendonly yes
dir /data
EOF
done

# 6. 哨兵配置（统一）
cat >/opt/redis/sentinel.conf <<'EOF'
bind 0.0.0.0
port 26379
protected-mode no
daemonize no
sentinel monitor mymaster 172.30.0.2 6379 2
sentinel auth-pass mymaster 123456
sentinel down-after-milliseconds mymaster 5000
sentinel parallel-syncs mymaster 1
sentinel failover-timeout mymaster 10000
EOF
for i in 1 2 3; do
  cp /opt/redis/sentinel.conf /opt/redis/sentinel$i/
done

# 7. 启动 Redis 主从（按顺序，IP 即 172.30.0.2/3/4）
docker run -d --name redis-master --network $NET -p 6379:6379 \
  -v /opt/redis/master/redis.conf:/usr/local/etc/redis/redis.conf:ro \
  -v /opt/redis/master/data:/data $IMG redis-server /usr/local/etc/redis/redis.conf

docker run -d --name redis-slave1 --network $NET -p 6380:6379 \
  -v /opt/redis/slave1/redis.conf:/usr/local/etc/redis/redis.conf:ro \
  -v /opt/redis/slave1/data:/data $IMG redis-server /usr/local/etc/redis/redis.conf

docker run -d --name redis-slave2 --network $NET -p 6381:6379 \
  -v /opt/redis/slave2/redis.conf:/usr/local/etc/redis/redis.conf:ro \
  -v /opt/redis/slave2/data:/data $IMG redis-server /usr/local/etc/redis/redis.conf

# 8. 启动哨兵（同一网络，IP 即 172.30.0.5/6/7）
for i in 1 2 3; do
  docker run -d --name sentinel$i --network $NET -p $((26379+i-1)):26379 \
    -v /opt/redis/sentinel$i/sentinel.conf:/usr/local/etc/redis/sentinel.conf \
    redis:7.0-alpine redis-sentinel /usr/local/etc/redis/sentinel.conf
done

# 9. 自检
sleep 5
echo ===== 主从 =====
docker exec redis-master redis-cli -a 123456 info replication | grep -E 'role|connected_slaves'
echo ===== 哨兵 =====
for i in 1 2 3; do
  printf "sentinel$i: "
  docker exec sentinel$i redis-cli -p 26379 info sentinel | grep -E 'sentinel_masters|slaves|sentinels' | tr '\n' ' '
  echo
done
